package com.whirl.ai_ml;

import cn.hutool.core.util.NumberUtil;
import ml.dmlc.xgboost4j.java.Booster;
import ml.dmlc.xgboost4j.java.DMatrix;
import ml.dmlc.xgboost4j.java.XGBoost;
import ml.dmlc.xgboost4j.java.XGBoostError;

import java.math.BigDecimal;

import static com.whirl.util.Constants.MLData_PATH;

/**
 * @author xw
 * @date 2022/8/17 9:58
 */
public class XGBoostModelRate {
    public static void main(String[] args) throws XGBoostError {
        DMatrix trainMat = new DMatrix(MLData_PATH + "load_rate/ai_ai.txt.train");
        DMatrix testMat = new DMatrix(MLData_PATH + "load_rate/ai_ai.txt.test");
        System.out.println("训练集样本个数：" + trainMat.getLabel().length);

        // 获取预测标签label的值
        float[] originLabel = testMat.getLabel();
        System.out.println("测试集样本个数：" + originLabel.length);
        System.out.print("实际值： ");
        for (float i : originLabel) {
            System.out.print(i + "  ");
        }
        System.out.println();

        // 加载模型
        Booster booster = XGBoost.loadModel(MLData_PATH + "load_rate/model/xgb_model.model");

        // 预测结果
        System.out.print("预测值： ");
        float[][] predicts = booster.predict(testMat);
        for (int i = 0; i < predicts.length; i++) {
            for (int j = 0; j < predicts[0].length; j++) {
                BigDecimal retain2 = NumberUtil.round(predicts[i][j], 2);
                predicts[i][j] = retain2.floatValue();
                System.out.print(predicts[i][0] + "  ");  // 写[i][j]结果也一样的，因为 predicts[0].length = 1
            }
        }
        System.out.print("\n误差：   ");

        // 预测值和实际值的差的绝对值
        float abs_error = 0;
        for (int i = 0; i < predicts.length; i++) {
            float err = Math.abs(predicts[i][0] - originLabel[i]);
            err = NumberUtil.round(err, 2).floatValue();
            System.out.print(err + "  ");
            abs_error += err;
        }
//        System.out.println("\n总误差： " + abs_error);
        System.out.println("\n平均误差： " + abs_error / predicts.length * 100 + "%");


    }
}
